package com.codeest.geeknews.component;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.codeest.geeknews.util.notify.DownloadNotifyBuilder;
import com.codeest.geeknews.util.okhttp.DownLoadObserver;
import com.codeest.geeknews.util.okhttp.DownloadInfo;
import com.codeest.geeknews.util.okhttp.DownloadManager;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * //@author Phoenix
 * private boolean isBindService;
 * private ServiceConnection conn = new ServiceConnection() {
 *
 * @Override public void onServiceConnected(ComponentName name, IBinder service) {
 * DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
 * DownloadService downloadService = binder.getService();
 * <p>
 * //接口回调，下载进度
 * downloadService.addOnProgressListener(new DownloadService.OnProgressListener() {
 * @Override public void onProgress(float fraction) {
 * Log.i(TAG, "下载进度：" + fraction);
 * <p>
 * //判断是否真的下载完成进行安装了，以及是否注册绑定过服务
 * if (fraction == DownloadService.UNBIND_SERVICE && isBindService) {
 * unbindService(conn);
 * isBindService = false;
 * ToastUtil.shortShow("下载完成！");
 * }
 * }
 * });
 * }
 * @Override public void onServiceDisconnected(ComponentName name) {
 * <p>
 * }
 * };
 * 用DownloadManager来实现版本更新
 * @date 2016-8-24 14:06
 */
public class OkhttpDownloadService extends Service {
    private static final String TAG = OkhttpDownloadService.class.getSimpleName();

    public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
    public final static String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
    public static final int HANDLE_DOWNLOAD = 0x001;
    public static final int HANDLE_DOWNLOAD_COMPLETE = 0x002;
    public static final String BUNDLE_KEY_DOWNLOAD_URL = "download_url";

    private Activity activity;
    private DownloadBinder binder;


    /**
     * 接收控制媒体播放的Intent，并做相应控制
     * <p>
     * 操作完成后，两件事
     * 发送Notification给RemoteView
     * 发送Intent给主Activity，更新其内部相关状态变量
     */
    private BroadcastReceiver downLoadBroadcast = new BroadcastReceiver() {
        // Called when the BroadcastReceiver gets an Intent it's registered to
        // receive
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "收到广播 ：" + action);
            DownloadInfo downloadInfo = intent.getParcelableExtra(DownloadNotifyBuilder.NOTIFICATION_EXRRA);
            if (DownloadNotifyBuilder.NOTIFICATION_ACTION_PAUSE.equals(action)) {
                DownloadManager.getInstance().stop(downloadInfo.getUrl());
            }
        }
    };

    //最新加入下载任务URL
    private String downloadUrl;
    private List<OnProgressListener> onProgressListeners = new ArrayList<>();

    public Handler downLoadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            for (OnProgressListener onProgressListener : onProgressListeners) {
                if (onProgressListener != null) {
                    if (HANDLE_DOWNLOAD == msg.what) {
                        //被除数可以为0，除数必须大于0
                        if (msg.arg1 >= 0 && msg.arg2 > 0) {
                            onProgressListener.onProgress(msg.arg1 / (float) msg.arg2, (DownloadInfo) msg.obj);
                        }
                    } else if (HANDLE_DOWNLOAD_COMPLETE == msg.what) {
                        onProgressListener.onComplete((DownloadInfo) msg.obj);
                    }
                }
            }
        }
    };


    @Override
    public void onCreate() {
        super.onCreate();
        binder = new DownloadBinder();
    }

    @Override
    public IBinder onBind(Intent intent) {
        //Log.i(TAG, "Apk下载路径传递成功：" + downloadUrl);
        //downloadUrl = intent.getStringExtra(BUNDLE_KEY_DOWNLOAD_URL);
        registerBroadcast();
        //downloadApk(downloadUrl);
        return binder;
    }

    public void startDownload(String url) {
        downloadUrl = url;
        Log.i(TAG, "开始新任务：" + downloadUrl);
        downloadApk(url);
    }

    /**
     * 下载最新APK
     */
    private void downloadApk(String url) {
        DownloadManager.getInstance().download(this, url, new DownLoadObserver() {
            @Override
            public void onNext(DownloadInfo value) {
                super.onNext(value);
                float fraction = value.getProgress() * 1f / value.getTotal();
                int progress = (int) (fraction * 100);
                @SuppressLint("DefaultLocale") String progressText = String.format("%d%%", progress);
                Log.i(TAG, "下载进度：progress=" + progressText + ", url=" + value.getUrl());
                //发送Handler消息更新进度和状态
                downLoadHandler.sendMessage(downLoadHandler.obtainMessage(HANDLE_DOWNLOAD, (int) value.getProgress(), (int) value.getTotal(), value));
            }

            @Override
            public void onComplete(DownloadInfo value) {
                if (downloadInfo != null) {
                    Log.i(TAG, "下载完成，" + downloadInfo.getFilePath());
                    downLoadHandler.sendMessage(downLoadHandler.obtainMessage(HANDLE_DOWNLOAD_COMPLETE, value));
                }
            }
        });
    }

    public LinkedHashMap<String, DownloadInfo> getDownloads() {
        return DownloadManager.getInstance().getDownloads();
    }

    /**
     * 注册广播
     */
    private void registerBroadcast() {
        /**注册service 广播 1.任务完成时 2.进行中的任务被点击*/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_DOWNLOAD_COMPLETE);
        intentFilter.addAction(ACTION_NOTIFICATION_CLICKED);
        intentFilter.addAction(DownloadNotifyBuilder.NOTIFICATION_ACTION_PAUSE);
        intentFilter.addAction(DownloadNotifyBuilder.NOTIFICATION_ACTION_PAUSE);
        registerReceiver(downLoadBroadcast, intentFilter);
        //TODO 注册取消下载等点击
        //registerReceiver(downLoadBroadcast = new DownLoadBroadcast(), intentFilter);
    }

    /**
     * 注销广播
     */
    private void unregisterBroadcast() {
        if (downLoadBroadcast != null) {
            unregisterReceiver(downLoadBroadcast);
            downLoadBroadcast = null;
        }
    }


    /**
     * 关闭定时器，线程等操作
     */
    private void close() {
        if (downLoadHandler != null) {
            downLoadHandler.removeCallbacksAndMessages(null);
        }
    }


    /**
     * 绑定此DownloadService的Activity实例
     *
     * @param activity
     */
    public void setTargetActivity(Activity activity) {
        this.activity = activity;
    }


    public class DownloadBinder extends Binder {
        /**
         * 返回当前服务的实例
         *
         * @return
         */
        public OkhttpDownloadService getService() {
            return OkhttpDownloadService.this;
        }

    }

    public interface OnProgressListener {
        /**
         * 下载进度
         *
         * @param fraction 已下载/总大小
         */
        void onProgress(float fraction, DownloadInfo downloadInfo);

        void onComplete(DownloadInfo downloadInfo);
    }

    /**
     * 对外开发的方法
     *
     * @param onProgressListener
     */
    public void addOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListeners.add(onProgressListener);
    }

    public void removeOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListeners.remove(onProgressListener);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterBroadcast();
        close();
        //unregisterContentObserver();
        Log.i(TAG, "下载任务服务销毁");
    }
}